package com.kafka.producer.config;

import com.kafka.producer.producer.Producer;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import static com.kafka.producer.config.RedisConfig.*;

@Component
public class TimedTask {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    Producer producer;

    @Scheduled(fixedRate = 10000)
    private void timeRun() {
        System.out.println("定时线程检查是否有发送失败的消息");
        // 检查redis中是否存在发送失败的消息
        Long size = stringRedisTemplate.opsForList().size(MSG_LIST + TOPIC);
        System.out.println("当前堆积的消息数："+size);
        if(size != null && size > 0) {
            System.out.println("发现有发送失败的消息");
            // 取出第一条信息
            String msg = stringRedisTemplate.opsForList().index(MSG_LIST + TOPIC, 0);
            if(msg != null) {
                String[] strArr = msg.split(":");
                int retryCount = Integer.parseInt(strArr[2]);
                System.out.println("当前重试次数："+retryCount);
                producer.sendMessage(strArr[1], strArr[0], Integer.parseInt(strArr[2]));
            }
        }
    }
}
